package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.DeteMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Badpheno;
import com.indusfo.spc.pojo.Dete;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.service.DeteService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DeteServiceImpl
 * @Description: 控制项目业务接口实现类
 * @author: 余家能
 * @date: 2018/11/26 上午9:31
 */
@Service
public class DeteServiceImpl implements DeteService {

    private static final Logger logger = LoggerFactory.getLogger(DeteServiceImpl.class);

    @Resource
    private DeteMapper deteMapper;

    @Resource
    private UploadMapper uploadMapper;

    /**
     * 查询控制项目
     *
     * @param dete
     * @return
     */
    @Override
    public JSONObject listDete(Dete dete) {

        try {

            Integer pagesize = dete.getPagesize();
            Integer pageindex = dete.getPageindex();
            if (pagesize != null && pageindex != null) {
                dete.setIncept(pagesize * (pageindex - 1));
            }

            // 查询记录数
            int count = deteMapper.getCounts(dete);

            List<Dete> detePros = deteMapper.listDete(dete);

            if (detePros.isEmpty()) {
                return JSONObject.oK("没有查询到控制项目相关数据", detePros, count);
            }

            //4.返回
            return JSONObject.oK("查询成功", detePros, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * @ClassName: DeteProServiceImpl
     * @Description: 插入控制项目
     * @author: 余家能
     * @date: 2018/11/26 上午10:07
     */
    @Override
    public JSONObject insertOrUpdateDete(Dete dete) {
        try {
            if (dete.getDeteId() != null) {// 有id,做更新
                validate(dete);
                Integer row = deteMapper.updateByPrimaryKeySelective(dete);
                if (row == 0) {
                    throw new ModifyFailedException("更新项目失败");
                }
                return JSONObject.oK("更新成功", row);
            } else {// 没id,做新增
                // 校验传入参数
                if (dete.getDataState() == null) {
                    dete.setDataState(1);
                }
                validate(dete);
                Integer row = deteMapper.insertSelective(dete);
                if (row == 0) {
                    throw new ModifyFailedException("新增控制项目失败");
                }
                return JSONObject.oK("新增成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }




    /**
     * @ClassName: DeteProServiceImpl
     * @Description: 删除
     * @author: 余家能
     * @date: 2018/11/26 上午10:09
     */
    @Override
    public JSONObject deleteDete(Long[] deteIds, Integer dataState) {

        try {
            //1.校验
            if (deteIds == null) {
                throw new ParamsErrorException("控制项目id不能为空");
            }
            if (dataState == null) {
                throw new ParamsErrorException("控制项目状态不能为空");
            }
            int row = deteMapper.deleteDete(deteIds, dataState);
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException(msg + "失败");
                    case 2:
                        throw new ModifyFailedException(msg + "失败");
                    case 3:
                        throw new ModifyFailedException(msg + "失败");
                }
            }
            return JSONObject.oK(msg + "成功", row);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 根据编码查重
     *
     * @param deteId
     * @param deteCode
     * @return
     */
    @Override
    public int getBydeteCode(Integer deteId, String deteCode) {
        return deteMapper.getBydeteCode(deteId, deteCode);
    }


    /**
     * 新增控制项目时，校验前端传递的参数
     *
     * @param
     */
    private void validate(Dete dete) {
        //控制项目id
        Integer deteId = dete.getDeteId();
        //控制项目编码
        String deteCode = dete.getDeteCode();
        //控制项目名称
        String deteName = dete.getDeteName();
        //不良现象ID
        Integer badphemeId = dete.getBadphenoId();
        //异常上报
        Integer errReport = dete.getErrUpload();
        //计量单位
        Integer deteUnitId = dete.getDeteUnitId();
        //仪器类型
        Integer insTypeId = dete.getInsTypeId();
        //项目类型
        Integer projectTypeId = dete.getProjectTypeId();
        //采集类型
        Integer gatherTypeId = dete.getGatherTypeId();
        if (StringUtils.isEmpty(deteName)) {
            throw new ParamsErrorException("控制项目名称不能为空");
        }
        if (deteName.getBytes().length > 100) {
            throw new ParamsErrorException("控制项目名称过长");
        }
        if (badphemeId == null) {
            throw new ParamsErrorException("不良现象ID不能为空");
        }
        if (errReport == null) {
            throw new ParamsErrorException("异常上报不能为空");
        }
        if (gatherTypeId == null) {
            throw new ParamsErrorException("采集单位不能为空");
        }
        if (projectTypeId == null) {
            throw new ParamsErrorException("采集类型不能为空");
        }
        if (deteUnitId == null) {
            throw new ParamsErrorException("计量单位不能为空");
        }
		/*
		if(deteUnit==null){
			throw new ParamsErrorException("计量单位不能为空");
		}
		if(StringUtils.isEmpty(standard)){
			throw new ParamsErrorException("项目标准不能为空");
		}
		*/
/*
		if (standard.getBytes().length > 100) {
			throw new ParamsErrorException("项目标准过长");
		}*/

        if (insTypeId == null) {
            throw new ParamsErrorException("仪器类型不能为空");
        }
        if (StringUtils.isEmpty(deteCode)) {
            throw new ParamsErrorException("控制项目编码不能为空");
        }
        if (deteCode.getBytes().length > 50) {
            throw new ParamsErrorException("控制项目编码超出规定,长度50");
        }
        if (getBydeteCode(deteId, deteCode) != 0) {
            throw new ParamsErrorException("控制项目编码已存在");
        }
    }

    @Override
    public String checkNoRepeat(Dete dete) {
        //获取仪器
        Map<String, Datadict> lInsTypeMap = uploadMapper.queryType(101006);
        //获取单位
        Map<String, Datadict> lDeteUnitMap = uploadMapper.queryType(101003);
        //采集类型
        Map<String, Datadict> gatherTypeMap = uploadMapper.queryType(101034);
        //项目类型
        Map<String, Datadict> projectTypeMap = uploadMapper.queryType(101042);
        //检测项目编码
        String deteCode = dete.getDeteCode();
        //检测项目名称
        String deteName = dete.getDeteName();
        //仪器类型名称
        String insTypeName = dete.getInsTypeName();
        //单位名称
        String deteUnitName = dete.getDeteUnitName();
        //采集类别名称
        String gatherTypeName = dete.getGatherTypeName();
        //项目类型名称
        String projectTypeName = dete.getProjectTypeName();

        //是否上报异常
        String errUploadName = dete.getErrUploadName();
        //不良现象名称
        String badphenoName = dete.getBadphenoName();
        if (StringUtils.isBlank(deteCode) && StringUtils.isBlank(deteName) && StringUtils.isBlank(insTypeName)
                && StringUtils.isBlank(deteUnitName) && StringUtils.isBlank(gatherTypeName) && StringUtils.isBlank(projectTypeName) && StringUtils.isBlank(errUploadName) && StringUtils.isBlank(badphenoName)) {
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if (StringUtils.isEmpty(deteCode)) {
            return "控制项目编码为空";
        }
        if (getBydeteCode(dete.getDeteId(), deteCode) != 0) {
            return "控制项目编码已存在";
        }
        if (deteCode.getBytes().length > 50) {
            return "控制项目编码超出规定,长度50个字节,25个汉字";
        }

        if (StringUtils.isEmpty(deteName)) {
            return "控制项目名称为空";
        }
        if (deteName.getBytes().length > 50) {
            return "控制项目名称过长,长度50个字节,25个汉字";
        }
        if (StringUtils.isEmpty(insTypeName)) {
            return "仪器类型名称为空";
        }
        if (!lInsTypeMap.containsKey(insTypeName)) {
            return "仪器类型名称填写不规范/错误";
        }
        //获取到仪器类型的id
        Datadict lInsTypeDatadict = lInsTypeMap.get(insTypeName);
        dete.setInsTypeId(lInsTypeDatadict.getItemId());
        if (StringUtils.isEmpty(deteUnitName)) {
            return "单位名称为空";
        }
        if (!lDeteUnitMap.containsKey(deteUnitName)) {
            return "单位名称填写错误/不规范";
        }
        //获取到单位名称的id
        Datadict lDeteUnitDatadict = lDeteUnitMap.get(deteUnitName);
        dete.setDeteUnitId(lDeteUnitDatadict.getItemId());
        if (StringUtils.isEmpty(gatherTypeName)) {
            return "采集类型为空";
        }
        if (!gatherTypeMap.containsKey(gatherTypeName)) {
            return "采集类型名称填写错误/不规范";
        }
        //获取采集类型的id
        Datadict gateherTypeDatadict = gatherTypeMap.get(gatherTypeName);
        dete.setGatherTypeId(gateherTypeDatadict.getItemId());
        if (StringUtils.isEmpty(projectTypeName)) {
            return "项目类型名称为空";
        }
        if (!projectTypeMap.containsKey(projectTypeName)) {
            return "项目类型名称填写错误/不规范";
        }
        //获取到项目类型的id
        Datadict projectTypeDatadict = projectTypeMap.get(projectTypeName);
        dete.setProjectTypeId(projectTypeDatadict.getItemId());
        if (StringUtils.isEmpty(errUploadName)) {
            return "是否上报异常为空";
        }
        if (!"是".equals(errUploadName) && !"否".equals(errUploadName)) {
            return "上报异常填写内容不规范";
        }
        if ("是".equals(errUploadName)) {
            dete.setErrUpload(1);
        }
        if ("否".equals(errUploadName)) {
            dete.setErrUpload(2);
        }
        if (StringUtils.isEmpty(badphenoName)) {
            return "不良现象名称为空";
        }
        Map<String, Badpheno> badphenoMap = uploadMapper.queryBadPheno();
        if (!badphenoMap.containsKey(badphenoName)) {
            return "不良现象名称填写不规范";
        }
        dete.setBadphenoId(badphenoMap.get(badphenoName).getBadphenoId());
        return null;
    }

    @Override
    public JSONObject updateListDete(List<Dete> deteProList) {

        int flag = uploadMapper.updateListDete(deteProList);
        if (flag > 0) {
            return JSONObject.oK("新增成功");
        }
        return JSONObject.oK("新增失败");
    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListDeteToInsert(Dete dete) {

        try {
            //获取页面的数据个数
            Integer pagesize = dete.getPagesize();
            //获取查询的页数
            Integer pageindex = dete.getPageindex();
            if (pagesize != null && pageindex != null) {
                dete.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<Dete> deteList = deteMapper.queryListDeteToInsert(dete);

            //如果页数和页面数量都不为空的情况下进行计数
            if (deteList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, deteList, 0);
            } else {
                Integer count = deteMapper.countDeteToInsert(dete);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, deteList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }


    }
}
